package com.zl.smartmall.library.im;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.loopj.android.http.RequestParams;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.im.vo.MessageInfoDao;
import com.zl.smartmall.library.im.vo.SessionInfoDao;
import com.zl.smartmall.library.listener.BaseListener;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.SingtonAsyncHttpClient;

/**　　　　　
 * 根据推送下来的消息id自动到服务器拉取消息内容的服务
 * @author 陈希然　
 */
public class IMService extends Service {

	private String TAG = IMService.class.getSimpleName();
	private MessageInfoDao mMessageDao;
	private SessionInfoDao mSessionDao;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		CrashHandler.d(TAG, TAG + "服务onCreate");
		mMessageDao = new MessageInfoDao(getApplicationContext());
		mSessionDao = new SessionInfoDao(getApplicationContext());
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		CrashHandler.d(TAG, TAG + "服务onStartCommand");
		if(intent != null) {
			if(Constants.ACTION_RECEIVE_IM_MESSAGE.equals(intent.getAction())) {
				handleReceiveAction(intent);
			
			}else if(Constants.ACTION_SEND_IM_TEXT_MESSAGE.equals(intent.getAction())) {
				handleSendTextAction(intent);
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		CrashHandler.d(TAG, TAG + "服务onDestroy");
	}
	
	private void handleReceiveAction(Intent intent) {
		int chatId = intent.getIntExtra("chatId", 0);
		int msgId = intent.getIntExtra("msgId", 0);
		receiveMessage(chatId, msgId);
		
	}
	
	private void handleSendTextAction(Intent intent) {
		String message = intent.getStringExtra("message");
		int toUid = intent.getIntExtra("toUid", 0);
		int queueId = intent.getIntExtra("queueId", 0);
		BaseListener listener = IM.getInstance().obtainListener(queueId);
		IM.getInstance().removeListener(queueId);
//		fuid	：必填，对方的uid
//		pmid	：选填，会话id
//		content	：选填，若 image 不存在，则content为必填
//		image	：选填，第一步里面图片的字段
//		width	：选填，第一步里面图片的字段
//		height	：选填，第一步里面图片的字段
		RequestParams params = new RequestParams();
		params.put("fuid", toUid);
		params.put("content", message);
		SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
		SingtonAsyncHttpClient.getInstance().post(Constants.URL_SEND_IM_MESSAGE, params, listener);
	}

	private void receiveMessage(int chatId, int msgId) {
//		String token = PreferenceModel.getString(Define.KEY_USER_TOKEN, "");
//		String verifyKey = Tools.obtainVerifyKey();
//		RequestParams params = new RequestParams();
//		params.put("token", token);
//		params.put("verifyKey", verifyKey);
//		params.put("verifyCode", Tools.md5(token + verifyKey));
//		params.put("chatID", chatId);
//		params.put("msgID", msgId);
//		mHttpClient.get(Define.URL_RECEIVE_PRIVATE_LETTER, params, new ReceiveMessageHttpHandler() {
//			
//			@Override
//			public void onReceiveMessageSuccess(final MessageInfo messageInfo) {
//				// TODO Auto-generated method stub
//				CrashHandler.d(TAG, messageInfo.toString());
//				messageInfo.setRelativeID(Tools.obtainRelativeChatID(
//						messageInfo.getReceiverUid(), messageInfo.getSenderUid()));
//				messageInfo.setDisplayLocation(Define.CHAT_MSG_DISPLAY_LOCATION_OTHER);
//				MessageWorker.getInstance().dispatchMessage(Define.OBSERVER_PRIVATE_LETTER,
//						messageInfo);
//				
//				final SessionInfo sessionInfo =  new SessionInfo();
//				sessionInfo.setFace(messageInfo.getSenderFace());
//				sessionInfo.setMessage(messageInfo.getMessage());
//				sessionInfo.setNickname(messageInfo.getSenderNickname());
//				sessionInfo.setUid(messageInfo.getSenderUid());
//				sessionInfo.setTime(System.currentTimeMillis());
//				MessageWorker.getInstance().dispatchMessage(Define.OBSERVER_SESSION_LIST, sessionInfo);
//				
//				ThreadExecutor.getInstance().execute(new Runnable() {
//					
//					@Override
//					public void run() {
//						// TODO Auto-generated method stub
//						mMessageDao.insert(messageInfo);
//						mSessionDao.delete(sessionInfo.getUid());
//						mSessionDao.insert(sessionInfo);
//					}
//				});
//			}
//			
//			@Override
//			public void onReceiveMessageFailure(int errorCode) {
//				// TODO Auto-generated method stub
//				CrashHandler.d(TAG, "私信获取失败");
//			}
//			
//			@Override
//			public void onError(Throwable error) {
//				// TODO Auto-generated method stub
//				CrashHandler.d(TAG, "私信获取失败");
//				
//			}
//		});
//		
//		CrashHandler.d(TAG, "url = " + Define.URL_RECEIVE_PRIVATE_LETTER + params);
	}

}
